<template>
  <div>
    <div class="page-header">
      <h1 class="page-title">药品管理</h1>
      <a-button type="primary" @click="showAddModal">
        <template #icon><plus-outlined /></template>
        添加药品
      </a-button>
    </div>
    
    <a-row :gutter="16" class="search-row">
      <a-col :xs="24" :md="8" :lg="6">
        <a-input-search
          v-model:value="searchText"
          placeholder="输入RFID ID或药品名称搜索"
          @search="handleSearch"
          enterButton
        />
      </a-col>
      <a-col>
        <a-button @click="refreshMedicines">
          <template #icon><reload-outlined /></template>
          刷新
        </a-button>
      </a-col>
    </a-row>
    
    <!-- Medicines Table -->
    <a-table
      :dataSource="filteredMedicines"
      :columns="columns"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'expiry'">
          <span :style="{ color: isExpired(record.expiry_date) ? 'red' : 'green' }">
            {{ formatDate(record.expiry_date) }}
            <a-tag v-if="isExpired(record.expiry_date)" color="red">已过期</a-tag>
            <a-tag v-else-if="isCloseToExpiry(record.expiry_date)" color="orange">即将过期</a-tag>
            <a-tag v-else color="green">有效期内</a-tag>
          </span>
        </template>
        <template v-if="column.key === 'batch'">
          <a-tag color="blue">{{ record.batch }}</a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space size="small">
            <a-button type="link" size="small" @click="viewDetail(record)">
              详情
            </a-button>
            <a-button type="link" size="small" @click="showTraceModal(record)">
              追溯
            </a-button>
            <a-button type="link" size="small" @click="showQRCode(record)">
              二维码
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>
    
    <!-- Add Medicine Modal -->
    <a-modal
      v-model:visible="addModalVisible"
      title="添加药品"
      @ok="handleAddOk"
      :confirmLoading="confirmLoading"
      width="600px"
    >
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="药品名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入药品名称" />
        </a-form-item>
        <a-form-item label="药品规格" name="spec">
          <a-input v-model:value="formState.spec" placeholder="请输入药品规格" />
        </a-form-item>
        <a-form-item label="生产厂家" name="manufacturer">
          <a-input v-model:value="formState.manufacturer" placeholder="请输入生产厂家" />
        </a-form-item>
        <a-form-item label="生产批次" name="batch">
          <a-input v-model:value="formState.batch" placeholder="请输入生产批次" />
        </a-form-item>
        <a-form-item label="生产日期" name="production_date">
          <a-date-picker
            v-model:value="formState.production_date"
            style="width: 100%"
            format="YYYYMMDD"
            value-format="YYYYMMDD"
          />
        </a-form-item>
        <a-form-item label="有效期至" name="expiry_date">
          <a-date-picker
            v-model:value="formState.expiry_date"
            style="width: 100%"
            format="YYYYMMDD"
            value-format="YYYYMMDD"
          />
        </a-form-item>
      </a-form>
      <div class="form-tip">
        <info-circle-outlined />
        <span>系统将自动生成RFID标识和防伪验证哈希</span>
      </div>
    </a-modal>
    
    <!-- Medicine Detail Modal -->
    <a-modal
      v-model:visible="detailVisible"
      title="药品详情"
      @ok="handleDetailOk"
      width="700px"
    >
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="RFID ID">
          <a-tag color="blue">{{ currentMedicine?.rfid_id }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="药品名称">
          {{ currentMedicine?.name }}
        </a-descriptions-item>
        <a-descriptions-item label="药品规格">
          {{ currentMedicine?.spec }}
        </a-descriptions-item>
        <a-descriptions-item label="生产厂家">
          {{ currentMedicine?.manufacturer }}
        </a-descriptions-item>
        <a-descriptions-item label="生产批次">
          <a-tag color="blue">{{ currentMedicine?.batch }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="生产日期">
          {{ formatDate(currentMedicine?.production_date) }}
        </a-descriptions-item>
        <a-descriptions-item label="有效期至">
          {{ formatDate(currentMedicine?.expiry_date) }}
          <a-tag v-if="isExpired(currentMedicine?.expiry_date)" color="red">已过期</a-tag>
          <a-tag v-else-if="isCloseToExpiry(currentMedicine?.expiry_date)" color="orange">即将过期</a-tag>
          <a-tag v-else color="green">有效期内</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="入库时间">
          {{ formatDateTime(currentMedicine?.created_at) }}
        </a-descriptions-item>
        <a-descriptions-item label="防伪验证哈希">
          <a-typography-paragraph copyable style="margin-bottom: 0">
            {{ currentMedicine?.verification_hash }}
          </a-typography-paragraph>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
    
    <!-- QR Code Modal -->
    <a-modal
      v-model:visible="qrCodeVisible"
      title="药品二维码"
      @ok="handleQRCodeOk"
      centered
    >
      <div style="text-align: center;">
        <div v-if="currentMedicine" class="qr-code-container">
          <!-- Placeholder for QR code -->
          <div class="qr-code">{{ currentMedicine.rfid_id }}</div>
        </div>
        <a-typography-paragraph style="margin-top: 16px; text-align: center;">
          药品RFID ID: {{ currentMedicine?.rfid_id }}
        </a-typography-paragraph>
        <a-button type="primary" @click="handleQRCodeOk">
          打印二维码
        </a-button>
      </div>
    </a-modal>
    
    <!-- Trace Modal -->
    <a-modal
      v-model:visible="traceModalVisible" 
      title="添加追溯事件"
      @ok="handleTraceOk"
      :confirmLoading="traceConfirmLoading"
    >
      <a-form
        :model="traceForm"
        :rules="traceRules"
        ref="traceFormRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="RFID ID" name="rfid_id">
          <a-input v-model:value="traceForm.rfid_id" disabled />
        </a-form-item>
        <a-form-item label="事件类型" name="event_type">
          <a-select v-model:value="traceForm.event_type" placeholder="请选择事件类型">
            <a-select-option value="storage">入库</a-select-option>
            <a-select-option value="transport">运输</a-select-option>
            <a-select-option value="sale">销售</a-select-option>
            <a-select-option value="verification">验证</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="事件地点" name="location">
          <a-input v-model:value="traceForm.location" placeholder="请输入事件地点" />
        </a-form-item>
        <a-form-item label="操作人员" name="operator">
          <a-input v-model:value="traceForm.operator" placeholder="请输入操作人员" />
        </a-form-item>
        <a-form-item label="备注信息" name="notes">
          <a-textarea v-model:value="traceForm.notes" placeholder="请输入备注信息" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, createVNode } from 'vue'
import { message, Modal } from 'ant-design-vue'
import moment from 'moment'
import api from '@/services/api'
import {
  PlusOutlined,
  InfoCircleOutlined,
  ReloadOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'

// Types
interface Medicine {
  rfid_id: string
  name: string
  spec: string
  manufacturer: string
  batch: string
  production_date: string
  expiry_date: string
  created_at: string
  verification_hash: string
}

interface MedicineForm {
  name: string
  spec: string
  manufacturer: string
  batch: string
  production_date: string
  expiry_date: string
}

interface TraceForm {
  rfid_id: string
  event_type: string
  location: string
  operator: string
  notes: string
}

// State
const medicines = ref<Medicine[]>([])
const loading = ref(true)
const searchText = ref('')

const addModalVisible = ref(false)
const confirmLoading = ref(false)
const formRef = ref(null)

const detailVisible = ref(false)
const currentMedicine = ref<Medicine | null>(null)

const qrCodeVisible = ref(false)

const traceModalVisible = ref(false)
const traceConfirmLoading = ref(false)
const traceFormRef = ref(null)

// Form state
const formState = reactive<MedicineForm>({
  name: '',
  spec: '',
  manufacturer: '',
  batch: '',
  production_date: '',
  expiry_date: ''
})

// Trace form state
const traceForm = reactive<TraceForm>({
  rfid_id: '',
  event_type: 'storage',
  location: '',
  operator: '',
  notes: ''
})

// Validation rules
const rules = {
  name: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
  spec: [{ required: true, message: '请输入药品规格', trigger: 'blur' }],
  manufacturer: [{ required: true, message: '请输入生产厂家', trigger: 'blur' }],
  batch: [{ required: true, message: '请输入生产批次', trigger: 'blur' }],
  production_date: [{ required: true, message: '请选择生产日期', trigger: 'change' }],
  expiry_date: [{ required: true, message: '请选择有效期', trigger: 'change' }]
}

// Trace validation rules
const traceRules = {
  event_type: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入事件地点', trigger: 'blur' }],
  operator: [{ required: true, message: '请输入操作人员', trigger: 'blur' }]
}

// Table columns
const columns = [
  {
    title: 'RFID ID',
    dataIndex: 'rfid_id',
    key: 'rfid_id',
    width: 170
  },
  {
    title: '药品名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '规格',
    dataIndex: 'spec',
    key: 'spec',
    width: 120
  },
  {
    title: '生产厂家',
    dataIndex: 'manufacturer',
    key: 'manufacturer'
  },
  {
    title: '批次',
    dataIndex: 'batch',
    key: 'batch',
    width: 100
  },
  {
    title: '有效期至',
    dataIndex: 'expiry_date',
    key: 'expiry',
    width: 200
  },
  {
    title: '操作',
    key: 'action',
    width: 200
  }
]

// Computed
const filteredMedicines = computed(() => {
  if (!searchText.value) return medicines.value
  const search = searchText.value.toLowerCase()
  return medicines.value.filter(medicine => 
    medicine.rfid_id.includes(search) || 
    medicine.name.toLowerCase().includes(search) ||
    medicine.manufacturer.toLowerCase().includes(search) ||
    medicine.batch.includes(search)
  )
})

// Methods
const refreshMedicines = async () => {
  loading.value = true
  try {
    const response = await api.getMedicines()
    const rfidIds = response.data.rfid_ids
    
    // Fetch details for each medicine
    const medicineDetails = await Promise.all(
      rfidIds.map(id => api.getMedicineByRfid(id))
    )
    
    medicines.value = medicineDetails.map(response => ({
      ...response.data
    }))
  } catch (error) {
    console.error('Failed to fetch medicines:', error)
    message.error('获取药品信息失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // searchText reactive triggers computed
}

const showAddModal = () => {
  addModalVisible.value = true
}

const resetForm = () => {
  if (formRef.value) {
    const form = formRef.value as any;
    if (form.resetFields) {
      form.resetFields();
    }
  }
}

const handleAddOk = async () => {
  try {
    if (!formRef.value) return
    
    const form = formRef.value as any;
    if (form.validate) {
      await form.validate();
    }
    
    confirmLoading.value = true
    
    // Add medicine
    const startTime = Date.now()
    await api.addMedicine(formState)
    const elapsed = Date.now() - startTime
    
    // Check performance requirement
    if (elapsed <= 2000) {
      message.success(`添加药品成功，用时 ${elapsed}ms`)
    } else {
      message.warning(`添加药品成功，但用时 ${elapsed}ms 超过了预期的2秒`)
    }
    
    addModalVisible.value = false
    resetForm()
    
    // Refresh medicines list
    await refreshMedicines()
  } catch (error) {
    console.error('Failed to add medicine:', error)
    message.error('添加药品失败，请检查输入')
  } finally {
    confirmLoading.value = false
  }
}

const viewDetail = (record: Medicine) => {
  currentMedicine.value = record
  detailVisible.value = true
}

const handleDetailOk = () => {
  detailVisible.value = false
}

const showQRCode = (record: Medicine) => {
  currentMedicine.value = record
  qrCodeVisible.value = true
}

const handleQRCodeOk = () => {
  qrCodeVisible.value = false
  message.success('二维码准备打印')
}

const showTraceModal = (record: Medicine) => {
  currentMedicine.value = record
  traceForm.rfid_id = record.rfid_id
  traceForm.event_type = 'storage'
  traceForm.location = ''
  traceForm.operator = '管理员'
  traceForm.notes = ''
  traceModalVisible.value = true
}

const handleTraceOk = async () => {
  try {
    if (!traceFormRef.value) return
    
    await traceFormRef.value.validate()
    traceConfirmLoading.value = true
    
    // Add trace event
    const startTime = Date.now()
    await api.addTraceEvent(traceForm)
    const elapsed = Date.now() - startTime
    
    message.success(`追溯事件记录成功，用时 ${elapsed}ms`)
    traceModalVisible.value = false
    
    // Show confirmation
    Modal.confirm({
      title: '追溯事件已记录',
      icon: createVNode(ExclamationCircleOutlined),
      content: '是否查看该药品的完整追溯历史？',
      okText: '查看追溯历史',
      cancelText: '关闭',
      onOk: () => {
        // Navigate to trace view
        // router.push({ path: `/trace`, query: { rfid: traceForm.rfid_id } })
        window.open(`/trace?rfid=${traceForm.rfid_id}`, '_blank')
      }
    })
  } catch (error) {
    console.error('Failed to add trace event:', error)
    message.error('添加追溯事件失败，请检查输入')
  } finally {
    traceConfirmLoading.value = false
  }
}

const formatDate = (dateStr: string | undefined): string => {
  if (!dateStr) return ''
  return moment(dateStr, 'YYYYMMDD').format('YYYY-MM-DD')
}

const formatDateTime = (dateTimeStr: string | undefined): string => {
  if (!dateTimeStr) return ''
  return moment(dateTimeStr).format('YYYY-MM-DD HH:mm:ss')
}

const isExpired = (dateStr: string | undefined): boolean => {
  if (!dateStr) return false
  return moment(dateStr, 'YYYYMMDD').isBefore(moment(), 'day')
}

const isCloseToExpiry = (dateStr: string | undefined): boolean => {
  if (!dateStr) return false
  const expiryDate = moment(dateStr, 'YYYYMMDD')
  const today = moment()
  const daysToExpiry = expiryDate.diff(today, 'days')
  return daysToExpiry >= 0 && daysToExpiry <= 30
}

// Lifecycle
onMounted(() => {
  refreshMedicines()
})
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-row {
  margin-bottom: 16px;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #1890ff;
  font-size: 14px;
}

.qr-code-container {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.qr-code {
  width: 200px;
  height: 200px;
  border: 1px solid #d9d9d9;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  color: #999;
  background: #f5f5f5;
}
</style> 